import os
import random

from PyQt5.QtCore import Qt
from PyQt5.QtGui import QFont, QPixmap
from PyQt5.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel, QPushButton,
                             QTextEdit, QComboBox, QSpinBox, QCheckBox, QGroupBox,
                             QMessageBox, QScrollArea, QSizePolicy, QLineEdit)

from database import get_db_connection


class StudyModeWidget(QWidget):
    def __init__(self, main_window):
        super().__init__()
        self.main_window = main_window
        self.current_question_index = 0
        self.questions = []
        self.setup_ui()

    def setup_ui(self):
        # 主布局
        main_layout = QVBoxLayout()

        # 添加返回按钮
        # self.back_btn = QPushButton("返回主界面")
        # self.back_btn.clicked.connect(self.return_to_main)
        # main_layout.addWidget(self.back_btn)

        # 筛选条件区域
        filter_group = QGroupBox("筛选条件")
        filter_layout = QHBoxLayout()

        self.type_combo = QComboBox()
        self.type_combo.addItem("所有类型", "")
        self.type_combo.addItem("填空题", "填空题")
        self.type_combo.addItem("选择题", "选择题")
        self.type_combo.addItem("判断题", "判断题")
        self.type_combo.addItem("综合题", "综合题")

        self.difficulty_combo = QComboBox()
        self.difficulty_combo.addItem("所有难度", 0)
        for i in range(1, 6):
            self.difficulty_combo.addItem(f"{i}星难度", i)

        self.category_combo = QComboBox()
        self.category_combo.addItem("所有分类", "")

        self.tags_edit = QLineEdit()
        self.tags_edit.setMinimumWidth(100)
        self.tags_edit.setPlaceholderText("标签筛选,用逗号分隔")

        self.favorite_check = QCheckBox("只收藏题")

        self.count_spin = QSpinBox()
        self.count_spin.setRange(1, 10000)
        self.count_spin.setValue(20)

        self.start_btn = QPushButton("开始刷题")
        self.start_btn.clicked.connect(self.start_study)

        filter_layout.addWidget(QLabel("类型:"))
        filter_layout.addWidget(self.type_combo)
        filter_layout.addWidget(QLabel("难度:"))
        filter_layout.addWidget(self.difficulty_combo)
        filter_layout.addWidget(QLabel("分类:"))
        filter_layout.addWidget(self.category_combo)
        filter_layout.addWidget(QLabel("标签:"))
        filter_layout.addWidget(self.tags_edit)
        filter_layout.addWidget(self.favorite_check)
        filter_layout.addWidget(QLabel("题数:"))
        filter_layout.addWidget(self.count_spin)
        filter_layout.addWidget(self.start_btn)

        filter_group.setLayout(filter_layout)
        main_layout.addWidget(filter_group)

        # 题目展示区域
        self.question_area = QScrollArea()
        self.question_area.setWidgetResizable(True)

        self.question_widget = QWidget()
        self.question_layout = QVBoxLayout(self.question_widget)

        # 题目编号和类型
        self.question_header = QLabel()
        self.question_layout.addWidget(self.question_header)

        # 题目内容
        self.content_label = QLabel()
        self.content_label.setWordWrap(True)
        self.question_layout.addWidget(self.content_label)

        # 题目图片
        self.content_image_label = QLabel()
        self.content_image_label.setAlignment(Qt.AlignCenter)
        self.question_layout.addWidget(self.content_image_label)

        # 答案区域 (初始隐藏)
        self.answer_group = QGroupBox("答案")
        self.answer_group.setVisible(False)
        answer_layout = QVBoxLayout()

        self.answer_label = QLabel()
        self.answer_label.setFont(QFont("Arial", 12))
        self.answer_label.setWordWrap(True)
        answer_layout.addWidget(self.answer_label)

        # 答案图片
        self.answer_image_label = QLabel()
        self.answer_image_label.setAlignment(Qt.AlignCenter)
        answer_layout.addWidget(self.answer_image_label)

        self.answer_group.setLayout(answer_layout)
        self.question_layout.addWidget(self.answer_group)

        # 备注区域
        self.notes_edit = QTextEdit()
        self.notes_edit.setPlaceholderText("可以添加备注信息...")
        self.notes_edit.setFont(QFont("Arial", 12))
        self.question_layout.addWidget(self.notes_edit)

        self.question_area.setWidget(self.question_widget)
        main_layout.addWidget(self.question_area)

        # 操作按钮区域
        button_layout = QHBoxLayout()

        self.prev_btn = QPushButton("上一题")
        self.prev_btn.clicked.connect(self.prev_question)

        self.show_answer_btn = QPushButton("显示答案")
        self.show_answer_btn.clicked.connect(self.toggle_answer)

        self.next_btn = QPushButton("下一题")
        self.next_btn.clicked.connect(self.next_question)

        self.favorite_btn = QPushButton("收藏")
        self.favorite_btn.setCheckable(True)
        self.favorite_btn.setStyleSheet('''
            QPushButton:checked {
                background: #42A5F5;
            }
        ''')
        self.favorite_btn.clicked.connect(self.toggle_favorite)

        self.save_btn = QPushButton("保存备注")
        self.save_btn.clicked.connect(self.save_notes)

        button_layout.addWidget(self.prev_btn)
        button_layout.addWidget(self.show_answer_btn)
        button_layout.addWidget(self.next_btn)
        button_layout.addStretch()
        button_layout.addWidget(self.favorite_btn)
        button_layout.addWidget(self.save_btn)

        main_layout.addLayout(button_layout)

        self.setLayout(main_layout)

        # 初始状态
        self.update_navigation_buttons()
        self.load_categories()


    def load_categories(self):
        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT DISTINCT category FROM questions WHERE category != '' ORDER BY category")
        categories = [row[0] for row in cursor.fetchall()]
        conn.close()

        self.category_combo.clear()
        self.category_combo.addItem("所有分类", "")
        for category in categories:
            self.category_combo.addItem(category, category)

    def start_study(self):
        # 获取筛选条件
        question_type = self.type_combo.currentData()
        difficulty = self.difficulty_combo.currentData()
        category = self.category_combo.currentData()
        tags = self.tags_edit.text().strip()
        only_favorite = self.favorite_check.isChecked()
        question_count = self.count_spin.value()

        # 构建查询条件
        conditions = []
        params = []

        if question_type:
            conditions.append("question_type = ?")
            params.append(question_type)

        if difficulty > 0:
            conditions.append("difficulty = ?")
            params.append(difficulty)

        if category:
            conditions.append("category = ?")
            params.append(category)

        if tags:
            tag_list = [tag.strip() for tag in tags.split(",") if tag.strip()]
            for tag in tag_list:
                conditions.append("tags LIKE ?")
                params.append(f"%{tag}%")

        if only_favorite:
            conditions.append("is_favorite = 1")

        # 查询符合条件的题目ID
        query = "SELECT id FROM questions"
        if conditions:
            query += " WHERE " + " AND ".join(conditions)

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(query, params)
        question_ids = [row[0] for row in cursor.fetchall()]
        conn.close()

        if not question_ids:
            QMessageBox.warning(self, "提示", "没有找到符合条件的题目!")
            return

        # 随机抽取指定数量的题目
        question_count = min(question_count, len(question_ids))
        self.questions = random.sample(question_ids, question_count)
        self.current_question_index = 0

        # 加载第一道题
        self.load_question()

    def load_question(self):
        if not self.questions or self.current_question_index >= len(self.questions):
            return

        question_id = self.questions[self.current_question_index]

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM questions WHERE id=?", (question_id,))
        row = cursor.fetchone()
        conn.close()

        if row:
            self.current_question = {
                'id': row[0],
                'question_type': row[1],
                'content': row[2],
                'content_image': row[3],
                'difficulty': row[4],
                'tags': row[5],
                'category': row[6],
                'answer': row[7],
                'answer_image': row[8],
                'notes': row[9],
                'is_favorite': row[10]
            }

            # 更新UI
            self.question_header.setText(
                f"题目 {self.current_question_index + 1}/{len(self.questions)} "
                f"[{self.current_question['question_type']}] "
                f"难度: {'★' * self.current_question['difficulty']}"
            )

            cc = self.current_question['content']
            parts = self.current_question['answer'].split("|")
            answer_text = ""
            if self.current_question['question_type'] == "选择题":
                options = parts[:-1]
                answer_text = "选项:\n" + "\n".join([f"{chr(65 + i)}. {option}" for i, option in enumerate(options)])

            self.content_label.setText(cc + answer_text)

            # 加载题目图片
            if self.current_question['content_image'] and os.path.exists(self.current_question['content_image']):
                pixmap = QPixmap(self.current_question['content_image'])
                if not pixmap.isNull():
                    # pixmap = pixmap.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    self.content_image_label.setPixmap(pixmap)
                    self.content_image_label.show()
                else:
                    self.content_image_label.hide()
            else:
                self.content_image_label.hide()

            # 处理答案
            answer_text = ""
            if self.current_question['question_type'] == "填空题":
                answers = self.current_question['answer'].split("|")
                answer_text = "参考答案:\n" + "\n".join([f"{i + 1}. {answer}" for i, answer in enumerate(answers)])
            elif self.current_question['question_type'] == "选择题":
                parts = self.current_question['answer'].split("|")
                if len(parts) > 1:
                    options = parts[:-1]
                    correct_answer = parts[-1]
                    # answer_text = "选项:\n" + "\n".join([f"{chr(65 + i)}. {option}" for i, option in enumerate(options)])
                    answer_text += f"\n\n正确答案: {correct_answer}"
            elif self.current_question['question_type'] == "判断题":
                answer_text = f"正确答案: {self.current_question['answer']}"
            else:  # 综合题
                answer_text = self.current_question['answer']

            self.answer_label.setText(answer_text)

            # 加载答案图片
            if self.current_question['answer_image'] and os.path.exists(self.current_question['answer_image']):
                pixmap = QPixmap(self.current_question['answer_image'])
                if not pixmap.isNull():
                    # pixmap = pixmap.scaled(600, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                    self.answer_image_label.setPixmap(pixmap)
                    self.answer_image_label.show()
                else:
                    self.answer_image_label.hide()
            else:
                self.answer_image_label.hide()

            # 备注
            self.notes_edit.setPlainText(self.current_question['notes'] or "")

            # 收藏状态
            self.favorite_btn.setChecked(self.current_question['is_favorite'])

            # 隐藏答案
            self.answer_group.setVisible(False)
            self.show_answer_btn.setText("显示答案")

            # 更新导航按钮状态
            self.update_navigation_buttons()

    def update_navigation_buttons(self):
        self.prev_btn.setEnabled(self.current_question_index > 0)
        self.next_btn.setEnabled(self.current_question_index < len(self.questions) - 1)

    def prev_question(self):
        if self.current_question_index > 0:
            self.current_question_index -= 1
            self.load_question()

    def next_question(self):
        if self.current_question_index < len(self.questions) - 1:
            self.current_question_index += 1
            self.load_question()

    def toggle_answer(self):
        if self.answer_group.isVisible():
            self.answer_group.setVisible(False)
            self.show_answer_btn.setText("显示答案")
        else:
            self.answer_group.setVisible(True)
            self.show_answer_btn.setText("隐藏答案")

    def toggle_favorite(self):
        if not hasattr(self, 'current_question'):
            return

        is_favorite = self.favorite_btn.isChecked()

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "UPDATE questions SET is_favorite=? WHERE id=?",
            (1 if is_favorite else 0, self.current_question['id'])
        )
        conn.commit()
        conn.close()

        self.current_question['is_favorite'] = is_favorite

    def save_notes(self):
        if not hasattr(self, 'current_question'):
            return

        notes = self.notes_edit.toPlainText().strip()

        conn = get_db_connection()
        cursor = conn.cursor()
        cursor.execute(
            "UPDATE questions SET notes=? WHERE id=?",
            (notes, self.current_question['id'])
        )
        conn.commit()
        conn.close()

        self.current_question['notes'] = notes
        QMessageBox.information(self, "成功", "备注已保存!")
